package modele;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.LinkedList;

import vue.ChatBox;
import vue.EcranAccueil;
import vue.JeuEchec;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

import com.example.finalprojet.R;

/**
 * Service Permettant de gérer le socket qui communique avec le serveur
 *
 * @author Maxime
 *
 */

public class SimpleService extends Service {

    
    private BufferedReader in = null;
	private PrintWriter out = null;
	private String pseudo = null;
    private Socket socket = null;   
    private String serverIpAddress = null;
 	private static final int REDIRECTED_SERVERPORT = 10000;
    private LinkedList<Messenger> mClients = new LinkedList<Messenger>();
    public static final int MSG_REGISTER_CLIENT = 1;
    public static final int MSG_UNREGISTER_CLIENT = 2;
    public static final int NOTIF_JEU = 3;
    public static final int MSG_SET_STRING_VALUE = 4;
    public static final int MSG_GET_PSEUDO = 5;
    public static final int MSG_GET_NUM_SALLE = 6;
    public static final int MSG_ADD_CHAT_ROOM = 7;
    public static final int MSG_MAJ_LIST = 8;
    public static final int MSG_SET_MSG = 9;
    public static final int MSG_SET_COUP = 10;
    public static final int NOTIF_NEWCHAT = 11;
    final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
    
   
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    
   
    @SuppressLint("HandlerLeak")
	class IncomingHandler extends Handler {  
    	@Override
        public void handleMessage(Message msg) {
        	
            switch (msg.what) {
            case MSG_REGISTER_CLIENT:

            	mClients.add(msg.replyTo);
                break;
                
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
     
            case MSG_SET_STRING_VALUE:
	             String str1 = msg.getData().getString("str1"); 
	             out.println(str1);
                break;
            case MSG_GET_PSEUDO:
            	 sendPseudoToUI();
            	 break;
            case NOTIF_JEU:
            	out.println(msg.getData().getString("str1"));
            	break;
            	
            	
            case MSG_ADD_CHAT_ROOM:
            	String str2 = msg.getData().getString("str1"); 
	             out.println(str2);
            	
            	break;
            	
           
         
 
                
             
            default:
              //  super.handleMessage(msg);
            	break;
            }
        }
    }
    private void sendMessageToUI(String intvaluetosend) {

    			
       
    			Log.e("SENDMESSAGETOUI", intvaluetosend);
    			
                Bundle b = new Bundle();
                b.putString("str1",intvaluetosend);
                Message msg = Message.obtain(null, MSG_SET_MSG);
                msg.setData(b);
                try{
                mClients.getLast().send(msg);
           
                }catch(Exception e){e.printStackTrace();}
                Log.e("SENDMESSAGETOUI", "FIN");
               
  
        }
    
    
    private void sendCoupToUI(String intvaluetosend) {

		
        
		Log.e("SENDMESSAGETOUI", intvaluetosend);
		
        Bundle b = new Bundle();
        b.putString("str1",intvaluetosend);
        Message msg = Message.obtain(null, MSG_SET_COUP);
        msg.setData(b);
        try{
        mClients.getLast().send(msg);
        }catch(Exception e){e.printStackTrace();}
        Log.e("SENDMESSAGETOUI", "FIN");
       

}
    
    
    private void sendPseudoToUI() {
       
              	
                  Bundle b = new Bundle();
                  b.putString("pseudo",pseudo);
                  Message msg = Message.obtain(null, MSG_GET_PSEUDO);
                  msg.setData(b);
                  try{
                	  for (int i = 0 ; i< mClients.size(); i++)
                  	mClients.get(i).send(msg);
                  }catch(Exception e){e.printStackTrace();}
                  

             
          }
    
    


    @Override
    public void onCreate() {
        super.onCreate();
        serverIpAddress = EcranAccueil.ADRESSEERVER;
        Log.e("Service Started", "Right");
     

        
      
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       // Log.i("MyService", "Received start id " + startId + ": " + intent);
        /////
        
        pseudo = intent.getStringExtra("pseudo");
        if (pseudo == null ) 
        pseudo = "Maxime";
        //////
        go go = new go();
        go.execute(pseudo);
        
       
        return START_NOT_STICKY; // run until explicitly stopped.
    }

   


    
    
    
    
    
    public class go extends AsyncTask<String, Void, Void>
	{
    	
    	private static final int ID_NOTIFICATION = 0;
		String theinput = null;

    	
  
		@Override
		protected Void doInBackground(String... arg0) {

		      try {
		         InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
		         socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
		         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		         out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
	             out.println(pseudo);
		         
		      } catch (UnknownHostException e1) {
		         e1.printStackTrace();
		      } catch (IOException e1) {
		         e1.printStackTrace();
		      }
		      
		      
		      while (true)
	  		  {

					try {
						theinput = in.readLine();
					} catch (IOException e1) {
						theinput="erreur%erreur";
						//e1.printStackTrace();
					}

					Log.e(pseudo+" ", theinput);
					
					String[] tab = theinput.split("%");
					Log.e(pseudo+" tab[0]  :",tab[0]);
					if ( tab[0].equals("msg") ) sendMessageToUI(tab[1]);
					
					
					
					if ( tab[0].equals("coup") ) sendCoupToUI(tab[1]);
					
					
					
					  
					if ( tab[0].equals("chat") ) 
					  {
						
						
						
						if ( tab[1].equals("incommingnewchat") )
						{
					//	sendNotification("Chatter avec "+ tab[3]);
							sendNotifChat(tab[2],tab[3]);
							
							/*
							ActivityManager am = (ActivityManager) SimpleService.this.
							getSystemService(Activity.ACTIVITY_SERVICE);
							String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
							String className = am.getRunningTasks(1).get(0).topActivity.getClassName();
							Log.e("Classname",className);
							
							if ( className.equalsIgnoreCase("dashboard")) sendNotification(tab[2]);
							*/
							//sendNotification("marchepas");
						}
						// tab[2] = room id
						// tab[3] = pseudo chat 
							/*
							Message msg = Message.obtain(null, NOTIF_NEWCHAT);
							Bundle b = new Bundle();
					    	b.putString("str1", tab[3]+"%"+tab[2]);
					    	msg.setData(b);
					    		   
					    	try{
					    		for ( int i = 0; i< mClients.size() ; i++)
					    	    	{mClients.get(i).send(msg);}        	
					    	   } catch (Exception e) {e.printStackTrace();}
						}*/
						/*
					    Intent i = new Intent(SimpleService.this, ChatBox.class);
					    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					    i.putExtra("num", tab[1]);
					    i.putExtra("nom", tab[2]);
					    startActivity(i);*/
					  }
					
					  if ( tab[0].equals("gojeu") ) 
					  {
						  
						Log.e(pseudo,"GOJEU");
						Intent i = new Intent(getApplicationContext(), JeuEchec.class);
				    	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				    	i.putExtra("num", tab[1]);
				    	i.putExtra("nom", tab[2]);
				    	i.putExtra("couleur", tab[3]);
				    	i.putExtra("pseudo", pseudo);
				   	    startActivity(i);
					  }
					  
					  if ( tab[0].equals("notifjeu") ) 
					  {
						Message msg = Message.obtain(null, NOTIF_JEU);
						Bundle b = new Bundle();
				    	b.putString("str1", tab[1]+"%"+tab[2]);
				    	msg.setData(b);
				    		   
				    	try{
				    		for ( int i = 0; i< mClients.size() ; i++)
				    	    	{mClients.get(i).send(msg);}        	
				    	   } catch (Exception e) {e.printStackTrace();}
				      }
					  
	  		  	}	
		      
		      
			
		}



		private void sendNotifChat(String numChat,String pseudo) {
			
			Message msg = Message.obtain(null, NOTIF_NEWCHAT);
			Bundle b = new Bundle();
	    	b.putString("str1",numChat+"%"+pseudo);
	    	msg.setData(b);
	    		   
	    	try{
	    		for ( int i = 0; i< mClients.size() ; i++)
	    	    	{mClients.get(i).send(msg);}        	
	    	   } catch (Exception e) {e.printStackTrace();}
			
		}



		@SuppressWarnings({ "unused", "deprecation" })
		private void sendNotification(String string) {
			
			
			
			  int icon = R.drawable.ic_action_search;
		        // Le premier titre affiché
		        CharSequence tickerText = "Titre de la notification";
		        // Daté de maintenant
		        long when = System.currentTimeMillis();
		 
		        // La notification est créée
		        Notification notification = new Notification(icon, tickerText, when);
		                 
		        Intent notificationIntent = new Intent(SimpleService.this, ChatBox.class);
		        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        PendingIntent contentIntent = PendingIntent.getActivity(SimpleService.this, 0, notificationIntent, 0);
		 
		        notification.setLatestEventInfo(SimpleService.this, "Chat", string, contentIntent);
		                 
		        // Récupération du Notification Manager
		        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		                 
		        manager.notify(ID_NOTIFICATION, notification);
			
		}
		
	
		

}
}